const express = require('express');
const cors = require('cors');
const { Low, JSONFile } = require('lowdb');
const path = require('path');

const app = express();
const PORT = 3000;

// 使用 JSON 文件作为数据库
const adapter = new JSONFile('db.json');
const db = new Low(adapter);

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 初始化数据库
async function initDB() {
  await db.read();
  db.data ||= { todos: [] };
  await db.write();
}

// 获取所有待办事项
app.get('/api/todos', async (req, res) => {
  await db.read();
  res.json(db.data.todos);
});

// 添加新的待办事项
app.post('/api/todos', async (req, res) => {
  const { text } = req.body;
  if (!text || text.trim() === '') {
    return res.status(400).json({ error: '待办事项不能为空' });
  }

  await db.read();
  const newTodo = {
    id: Date.now(),
    text: text.trim(),
    completed: false,
    createdAt: new Date().toISOString()
  };
  
  db.data.todos.push(newTodo);
  await db.write();
  
  res.status(201).json(newTodo);
});

// 更新待办事项状态
app.put('/api/todos/:id', async (req, res) => {
  const { id } = req.params;
  const { completed, text } = req.body;

  await db.read();
  const todo = db.data.todos.find(t => t.id === parseInt(id));
  
  if (!todo) {
    return res.status(404).json({ error: '待办事项未找到' });
  }

  if (completed !== undefined) todo.completed = completed;
  if (text !== undefined) todo.text = text.trim();
  
  await db.write();
  res.json(todo);
});

// 删除待办事项
app.delete('/api/todos/:id', async (req, res) => {
  const { id } = req.params;
  
  await db.read();
  db.data.todos = db.data.todos.filter(t => t.id !== parseInt(id));
  await db.write();
  
  res.status(204).send();
});

// 启动服务器
async function startServer() {
  await initDB();
  app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log('API 端点:');
    console.log('  GET    /api/todos    - 获取所有待办事项');
    console.log('  POST   /api/todos    - 添加新的待办事项');
    console.log('  PUT    /api/todos/:id - 更新待办事项');
    console.log('  DELETE /api/todos/:id - 删除待办事项');
  });
}

startServer().catch(console.error);
